package com.example.myapplication.view

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.Gravity
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import com.blankj.utilcode.util.SizeUtils
import com.example.myapplication.R
import com.example.myapplication.shortvideo.utils.ImageUtil

/**
 * @作者 ：lybin
 * @日期：2023.05.22
 * 叠加头像列表控件，可以分区左右，最大数量
 */
class AvatarListView : FrameLayout {

    /** 头像外圆圈的宽带 */
    var mStrokeWidth = SizeUtils.dp2px(1f)

    /** 头像的宽高，默认 20 dp */
    var mHeadWH = SizeUtils.dp2px(20f)


    /** 是否是右边模式 */
    var mIsRightModel = false

    var origenList: List<String>? = null

    var mLoopIndex = -1

    var maxNun = 4
    var mOverlayDp = 0f

    var animatorSet: AnimatorSet? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    /**
     * 增加头像
     *
     * @param list             头像地址
     * @param maxNun           头像最大个数
     * @param overlayDp        头像叠加区域
     * @param isRightModel     右边是否在下
     * @param scaleMax         放大的最大值
     */
    fun addHeaderView(
        list: List<String>?,
        maxNun: Int = 4,
        overlayDp: Float = 4F,
        isRightModel: Boolean = false
    ) {
        if (list == null || list.isEmpty()) {
            return
        }
        this.maxNun = maxNun
        this.mIsRightModel = isRightModel
        this.mOverlayDp = overlayDp
        removeAllViews()
        val vlp = layoutParams
        origenList = list
        val targetList = list.subList(0, maxNun.coerceAtMost(list.size))
        var allWidth = 0
        val itemMargin = mHeadWH - SizeUtils.dp2px(overlayDp)
        if (isRightModel) {
            // 倒序
            val index = targetList.size - 1
            for (i in index downTo 0) {
                val margin: Int = i * itemMargin
                addView(
                    createHeadImageView(
                        targetList[i],
                        Color.WHITE,
                        mStrokeWidth,
                        margin,
                        R.mipmap.ic_launcher_round
                    )
                )
            }
        } else {
            for (i in targetList.indices) {
                val margin: Int = i * itemMargin
                addView(
                    createHeadImageView(
                        targetList[i],
                        Color.WHITE,
                        mStrokeWidth,
                        margin,
                        R.mipmap.ic_launcher_round
                    )
                )
            }
        }

        val dataSize = targetList.size
        allWidth += mHeadWH * dataSize - (dataSize - 1) * (mHeadWH - itemMargin)
        vlp.width = allWidth
        layoutParams = vlp
    }


    /**
     * 增加头像，固定数量，不足的头像，使用默认图
     *
     * @param list             头像地址
     * @param fixedNun         头像固定个数
     * @param overlayDp        头像叠加区域
     * @param isRightModel     右边是否在下
     */
    fun addHeaderViewWithFixedNum(
        list: List<String>?,
        fixedNun: Int = 4,
        overlayDp: Float = 4F,
        isRightModel: Boolean = false,
        placeholder: Int,
        haveBoss: Boolean,
        reverse: Boolean = false,
        fullFixedNum: Boolean = true
    ) {

        mIsRightModel = isRightModel

        removeAllViews()
        val vlp = layoutParams
        vlp.height = mHeadWH

        val listSize = if (list.isNullOrEmpty()) {
            fixedNun
        } else {
            list.size
        }

        val targetList = if (list.isNullOrEmpty()) {
            ArrayList()
        } else {
            list.subList(0, fixedNun.coerceAtMost(listSize))
        }

        var allWidth = 0
        val itemMargin = mHeadWH - SizeUtils.dp2px(overlayDp)
        val listEmpty: Boolean = list.isNullOrEmpty()
        var default = placeholder
        var realPosition: Int
        if (isRightModel) {
            val index = if (fullFixedNum) fixedNun - 1 else targetList.size - 1
            // 倒序
            for (i in index downTo 0) {
                var color = Color.WHITE
                val margin: Int = i * itemMargin
                realPosition = if (reverse) index - i else i
                val url = if (listEmpty || realPosition >= listSize) {
                    ""
                } else {
                    targetList[realPosition]
                }
                if (haveBoss && realPosition == 0) {
                    color = Color.parseColor("#FFE333")
                    if (url.isEmpty()) {
                        default = R.mipmap.ic_launcher_round
                        color = Color.WHITE
                    }
                }
                addView(
                    createHeadImageView(
                        url,
                        color,
                        mStrokeWidth,
                        margin,
                        default
                    )
                )
            }
        } else {
            for (i in 0 until if (fullFixedNum) fixedNun else targetList.size) {
                val margin: Int = i * itemMargin
                realPosition = if (reverse) fixedNun - 1 - i else i
                val url = if (listEmpty || realPosition >= listSize) {
                    ""
                } else {
                    targetList[realPosition]
                }
                addView(
                    createHeadImageView(
                        url,
                        Color.WHITE,
                        mStrokeWidth,
                        margin,
                        placeholder
                    )
                )
            }
        }

        allWidth += mHeadWH * fixedNun - (fixedNun - 1) * (mHeadWH - itemMargin)
        vlp.width = allWidth
        layoutParams = vlp
    }


    /**
     * 创建圆形头像
     *
     * @param headUrl     头像地址
     * @param strokeColor 边框颜色
     * @param strokeWidth 边框宽度
     * @param leftMargin  左边距
     * @return
     */
    private fun createHeadImageView(
        headUrl: String,
        strokeColor: Int,
        strokeWidth: Int,
        leftMargin: Int,
        placeholder: Int
    ): ImageView {
        val imageView = ImageView(context)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        val imageLayoutParams = LayoutParams(mHeadWH, mHeadWH)
        imageLayoutParams.leftMargin = leftMargin
        imageLayoutParams.gravity = Gravity.CENTER_VERTICAL
        imageView.layoutParams = imageLayoutParams
        ImageUtil.display(headUrl,imageView,R.mipmap.ic_launcher_round,100,100)
//        imageView.setImageResource(R.mipmap.ic_launcher_round)
        return imageView
    }

    var mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                startLoopAnime(false)
            }
        }
    }


    public fun startLoopAnime(first: Boolean) {
        if (origenList == null) {
            return
        }
        if (origenList!!.size > maxNun) {
            mLoopIndex--
            if (first) {
                mLoopIndex = origenList!!.size - maxNun - 1

                layoutParams.width += mHeadWH
            } else {
                val itemMargin = mHeadWH - SizeUtils.dp2px(mOverlayDp)
                for (i in 0 until childCount - 1) {
                    val itemView = getChildAt(i)
                    (itemView.layoutParams as MarginLayoutParams).leftMargin += itemMargin
                }
            }
            if (mLoopIndex <= 0) {
                mLoopIndex = origenList!!.size - 1
            }

            val index0View = getChildAt(0)

            val translationXList = mutableListOf<ObjectAnimator>()
            for (i in 0 until childCount) {
                val itemView = getChildAt(i)
                val translationX = ObjectAnimator.ofFloat(
                    itemView,
                    "translationX",
                    0f,
                    mHeadWH.toFloat() - SizeUtils.dp2px(mOverlayDp)
                ).setDuration(600)
                translationXList.add(translationX)

                if (i == 0) {
                    val alpha = ObjectAnimator.ofFloat(itemView, "alpha", 1f, 0f).setDuration(600)
                    translationXList.add(alpha)
                }
            }

            val newView = createHeadImageView(
                origenList!![mLoopIndex],
                Color.WHITE,
                mStrokeWidth,
                0,
                R.mipmap.ic_launcher_round
            )

            val alpha = ObjectAnimator.ofFloat(newView, "alpha", 0.5f, 1f).setDuration(200)
            translationXList.add(alpha)
            addView(newView)

              animatorSet = AnimatorSet()
            animatorSet?.addListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) {

                }

                override fun onAnimationEnd(animation: Animator?) {
                    if (index0View != null) {
                        removeView(index0View)
                    }
                    mHandler.sendEmptyMessageDelayed(1, 3000)
                }

                override fun onAnimationCancel(animation: Animator?) {
                }

                override fun onAnimationStart(animation: Animator?) {
                }
            })
            animatorSet?.playTogether(translationXList.toList())
            animatorSet?.duration = 600
            animatorSet?.interpolator = LinearInterpolator()
            animatorSet?.start()
        }
    }


    public fun stopLoopAnime() {
        mHandler.removeMessages(1)
        animatorSet?.removeAllListeners()
        animatorSet?.cancel()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopLoopAnime()
    }


}